// 1.插件：挂载$store
// 2.实现Store
let Vue;

class Store {
    constructor(options) {
        this._vm = new Vue({
            data: {
                $$state: options.state
            }
        })

        this._mutations = options.mutations
        this._actions = options.actions
        this.commit = this.commit.bind(this)
        this.dispatch = this.dispatch.bind(this)
        this.getters = {}

    }

    get state() {
        return this._vm._data.$$state
    }

    set state(v) {
        console.error('please use replaceState to reset state')
    }

    commit(type, payload) {
        const entry = this._mutations[type]
        if (!entry) {
            console.error('unkown mutation type');
        }
        entry(this, payload)
    }

    dispatch(type, payload) {
        const entry = this._actions[type]
        if (!entry) {
            console.error('unkown action type');
        }

        entry(this, payload)
    }
}


// 参数1 Vue构造函数

function install(_Vue) {
    Vue = _Vue; //接收_vue构造器
    // 混入 Vue.mixin({})
    Vue.mixin({
        beforeCreate() {
            // 延迟执行  
            //判断 根 实例 有没有传入store 数据源,
            //如果传入了, 就把它放到实例的 $store上
            if (this.$options.store) {
                Vue.prototype.$store = this.$options.store

            }
        }
    })
}

export default {
    Store,
    install
}